package com.library.controller;

import com.library.dto.ReservationDTO;
import com.library.service.ReservationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 预约控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/books")
@RequiredArgsConstructor
public class ReservationController {
    private final ReservationService reservationService;

    /**
     * 预约图书接口
     * POST /api/books/{id}/reserve
     */
    @PostMapping("/{id}/reserve")
    public ResponseEntity<Map<String, String>> reserveBook(
            @PathVariable Long id,
            @RequestAttribute Long userId) {
        reservationService.reserveBook(userId, id);
        Map<String, String> response = new HashMap<>();
        response.put("message", "预约成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 获取预约列表接口
     * GET /api/books/reservations
     */
    @GetMapping("/reservations")
    public ResponseEntity<Map<String, List<ReservationDTO>>> getReservations(
            @RequestAttribute Long userId,
            @RequestAttribute String role) {
        boolean isAdmin = "admin".equals(role);
        List<ReservationDTO> reservations = reservationService.getReservations(userId, isAdmin);
        Map<String, List<ReservationDTO>> response = new HashMap<>();
        response.put("reservations", reservations);
        return ResponseEntity.ok(response);
    }

    /**
     * 取消预约接口
     * DELETE /api/books/reservations/{id}
     */
    @DeleteMapping("/reservations/{id}")
    public ResponseEntity<Map<String, String>> cancelReservation(
            @PathVariable Long id,
            @RequestAttribute Long userId) {
        reservationService.cancelReservation(userId, id);
        Map<String, String> response = new HashMap<>();
        response.put("message", "取消预约成功");
        return ResponseEntity.ok(response);
    }
}

